package valoskmdev.dao;

import java.util.List;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;

import valoskmdev.bean.AppUser;
import valoskmdev.bean.Vehicle;
import valoskmdev.util.Utils;

public class VehicleDao {

	private VehicleDao() {
	}

	public static Vehicle insertNew(final PersistenceManager pm, final AppUser appUser, Vehicle vehicle) {
		
		appUser.getVehicles().add(vehicle);
		pm.makePersistent(appUser);
		pm.makePersistent(vehicle);

		return vehicle;
	}

	@SuppressWarnings("unchecked")
	public static List<Vehicle> getVehicles(final PersistenceManager pm, final String wordToSearch) {

		final Query query = pm.newQuery(Vehicle.class);
		if (!Utils.isEmptyOrNull(wordToSearch)) {
			query.setFilter("vin == param && isDisabled == false");
		}
		query.declareParameters("String param");
		query.setRange(0, 20);
		List<Vehicle> vehicles = (List<Vehicle>) query.execute(wordToSearch);
		if (vehicles.isEmpty()) {
			if (!Utils.isEmptyOrNull(wordToSearch)) {
				query.setFilter("regNumber == param && isDisabled == false");
			}
			vehicles = (List<Vehicle>) query.execute(wordToSearch);
		}
		return vehicles;

	}

	public static Vehicle getVehicle(final PersistenceManager pm, final String searchParam) {

		try {
			final Query query = pm.newQuery(Vehicle.class, "publicKey == searchParam && isDisabled != true");
			query.declareParameters("String searchParam");
			query.setUnique(true);
			return (Vehicle) query.execute(searchParam);
		} catch (final Exception ex) {
			return null;
		}

	}

}